#include "../common/dispatch.hpp"
#include "../common/net.hpp"
#include "../common/message.hpp"
#include "../server/rpc_router.hpp"
#include <thread>


//将Add方法注册到rpcrouter中进行管理，设置为rpcrouter中的回调函数，再把rpcrouter中的onresponse函数设置为dispatch模块中的回调函数，最后
//把dispatch中的回调函数设置为server中的回调函数
void Add(const Json::Value& req,Json::Value& rsp)
{
    rsp = req["num1"].asInt() + req["num2"].asInt();
}

int main()
{
    auto dispatcher = std::make_shared<rpc::Dispatcher>();
    
    auto router = std::make_shared<rpc::server::RpcRouter>();
    std::unique_ptr<rpc::server::SDescribeFactory> desc_factory = std::make_unique<rpc::server::SDescribeFactory>();
    desc_factory->setmethod("Add");//设置方法名称
    desc_factory->setParamsdesc("num1",rpc::server::VType::INTEGRAL);//设置参数
    desc_factory->setParamsdesc("num2",rpc::server::VType::INTEGRAL);
    desc_factory->setVtype(rpc::server::VType::INTEGRAL);//设置返回值类型
    desc_factory->setCallback(Add);

    router->RegisterMethod(desc_factory->build());
    auto cb = std::bind(&rpc::server::RpcRouter::onRpcRequest,router.get(),std::placeholders::_1,std::placeholders::_2);

    dispatcher->registerHandler<rpc::RpcRequest>(rpc::Mtype::REQ_RPC,cb);
    
    auto server = rpc::ServerFactory::create(9090);
    auto msg_cb = std::bind(&rpc::Dispatcher::onMessage,dispatcher.get(),std::placeholders::_1,std::placeholders::_2);
    server->setMessageCallback(msg_cb);
    
    server->start();
    return 0;   
}

